package org.elfen.option;

import javax.servlet.http.HttpServletRequest;

import org.elfen.common.Constants;
import org.elfen.common.Token;
import org.elfen.common.filter.BaseTokenFilterOption;
import org.elfen.common.util.DataUtil;
import org.elfen.common.util.WebUtil;
import org.elfen.redis.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 实现BaseTokenFilterOption 接口，完成对Token的校验
 */
@Service
public class SysTokenFilterActionImpl implements BaseTokenFilterOption {
	private static final Logger logger = LoggerFactory.getLogger(SysTokenFilterActionImpl.class);
	@Autowired
	private RedisService redisService;
	
	@Override
	public void validateTokenInfo(String tokenKey, HttpServletRequest request) {
		Token tokenInfo = redisService.selectToken2Redis(tokenKey);
		logger.debug("进行token验证,tokenInfo={}",tokenInfo);
		if (DataUtil.isNotEmpty(tokenInfo)) {
			//清除当前session中的user
			WebUtil.removeCurrentUser(request);
			Long now = System.currentTimeMillis();
			if (now - tokenInfo.getTime() < 1000 * Integer.parseInt(Constants.TOKEN_EXPIRATION)) {
				String userId = tokenInfo.getUserId();
				//重新设置Token过期时间
				redisService.saveToken2Redis(tokenInfo);
				//将userId添加到但是session中
				WebUtil.saveCurrentUser(request, userId);
			}
		}
	}

}
